package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.historyRFC;

import java.sql.ResultSet;
import java.util.ArrayList;

import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.HistoryMaker;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.database.DatabaseConnection;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.model.History;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.model.User;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.historyRFCPanel.HistoryRFCPanel;

public class LoadHistoryThread extends Thread
{
	private DatabaseConnection connection;
	private HistoryRFCPanel historyRFCPanel;
	
	public LoadHistoryThread(HistoryRFCPanel historyRFCPanel, User signedInUser)
	{
		this.historyRFCPanel = historyRFCPanel;
	}

	public void run()
	{
		this.connection = new DatabaseConnection();
		historyRFCPanel.getHistoryRFCFunctionPanel().getProgress().setVisible(true);
		
		historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().setVisible(false);
		connection.connect();

		String query = "SELECT * FROM cms_history ORDER BY "+History.TC_SOURCE;
		ResultSet rs = connection.query(query);

		historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().clearTable();

		ArrayList<History> historyList = new ArrayList<History>();
		int count = 0;
		try
		{
			while(rs.next())
			{
				HistoryMaker maker = new HistoryMaker();
				historyList.add(maker.createHistoryEntry(rs));
				count++;
			}
		} catch (Exception e) {
		}

		if(count == 0)
		{
			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().displayNoEntry();
		}
		else
		{

			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().setVisible(false);
			for(History history : historyList)
			{
				this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().addEntryToTable(history);
			}
			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().setVisible(true);
		}
		historyRFCPanel.getHistoryRFCFunctionPanel().getSerchfield().setText("");
		historyRFCPanel.getHistoryRFCFunctionPanel().getProgress().setVisible(false);
		connection.disconnect();
	}
}